import React, { useEffect, useState, useRef } from 'react';
import {
  Modal,
  Tabs,
  Typography,
  List,
  Avatar,
  Space,
  Tag,
  Button,
  Divider,
  Image,
  Spin,
  message,
  Card,
  Row,
  Col,
  Input,
  Select,
  Progress,
  Tooltip,
  Dropdown,
  Menu,
  Alert,
  Drawer,
  Badge,
  Empty
} from 'antd';
import {
  LikeOutlined,
  CommentOutlined,
  ShareAltOutlined,
  EyeOutlined,
  EditOutlined,
  StarOutlined,
  StarFilled,
  LinkOutlined,
  FireOutlined,
  SendOutlined,
  ThunderboltOutlined,
  BookOutlined,
  ExperimentOutlined,
  SwapOutlined,
  BulbOutlined,
  SafetyCertificateOutlined,
  CopyOutlined,
  RobotOutlined,
  DownloadOutlined,
  SettingOutlined,
  HistoryOutlined,
  FileTextOutlined,
  BugOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';

// Types
import { HotItemDetail, Comment } from '../../../types/hotRadar';
import { platformConfig } from '../../../constants/platforms';

// Services
import { hotRadarService } from '../../../services/hotRadar.service';
import { generationService } from '../../../services/generation.service';
import { aiGenerationService } from '../../../services/ai-generation.service';
import { qualityService } from '../../../services/quality.service';
import { optimizationService } from '../../../services/optimization.service';

// Stores
import { useHotRadarStore } from '../../../stores/hotRadar.store';
import { useModelConfigStore } from '../../../stores/model-config.store';
import { usePromptStore } from '../../../stores/prompt.store';
import { useConversationStore } from '../../../stores/conversation.store';

// Hooks
import { useBreakpoint } from '../../../hooks/useBreakpoint';

// Components - 提示词管理
import PromptSelector from '../../conversation/PromptSelector';
import PromptEditor from '../../conversation/PromptEditor';
import PromptLibrary from '../../conversation/PromptLibrary';
import PromptTester from '../../conversation/PromptTester';

// Components - 模型对比与优化
import { ModelComparison } from '../../multi-model/ModelComparison';
import MultiModelDebugPanel from '../../multi-model/MultiModelDebugPanel';
import OptimizationPanel from '../../optimization/OptimizationPanel';

// Components - 参数控制
import ParameterPanel from '../../conversation/ParameterPanel';
import ModelStatusIndicator from '../../conversation/ModelStatusIndicator';

// Components - 图表
import { HeatTrendChart } from '../HeatTrendChart';

// Components - 富文本编辑器
import RichTextEditor from '../../common/RichTextEditor';

import './style.css';

const { Title, Text, Paragraph, Link } = Typography;
const { TabPane } = Tabs;
const { TextArea } = Input;
const { Option } = Select;

interface HotCreatorModalProps {
  visible: boolean;
  item: any;
  defaultTab?: string; // 新增：默认打开的tab ('detail' | 'create')
  onClose: () => void;
}

export const HotCreatorModal: React.FC<HotCreatorModalProps> = ({
  visible,
  item,
  defaultTab = 'detail',
  onClose,
}) => {
  // ========== 基础状态 ==========
  const [loading, setLoading] = useState(false);
  const [detailData, setDetailData] = useState<HotItemDetail | null>(null);
  const [activeTab, setActiveTab] = useState('create');
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';
  
  // ========== Store Hooks ==========
  const { favoriteIds, toggleFavorite } = useHotRadarStore();
  const { configs, loadConfigs } = useModelConfigStore();
  const { 
    prompts, 
    currentPrompt, 
    loadPrompts, 
    selectPrompt,
    updatePrompt 
  } = usePromptStore();
  const { sendMessage, isGenerating } = useConversationStore();
  
  // ========== 创作相关状态 ==========
  const [selectedModel, setSelectedModel] = useState<string>('');
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [generatedContent, setGeneratedContent] = useState('');
  const [qualityScore, setQualityScore] = useState<number | null>(null);
  const [originalityScore, setOriginalityScore] = useState<number | null>(null);
  const [localGenerating, setLocalGenerating] = useState(false);
  const [generateProgress, setGenerateProgress] = useState(0);
  const [generateStatus, setGenerateStatus] = useState('');

  // ========== 微调功能状态 ==========
  const [refineInput, setRefineInput] = useState('');
  const [isRefining, setIsRefining] = useState(false);
  const [refineHistory, setRefineHistory] = useState<Array<{
    timestamp: string;
    requirement: string;
    beforeContent: string;
    afterContent: string;
  }>>([]);
  const [contentVersions, setContentVersions] = useState<Array<{
    version: number;
    content: string;
    timestamp: string;
  }>>([]);
  const [currentVersion, setCurrentVersion] = useState(0);

  // ========== 段落选择和组合功能状态 ==========
  const [contentParagraphs, setContentParagraphs] = useState<Array<{
    id: string;
    content: string;
    selected: boolean;
  }>>([]);
  const [showParagraphSelector, setShowParagraphSelector] = useState(false);
  const [composedArticle, setComposedArticle] = useState('');
  const [rawContent, setRawContent] = useState(''); // 新增：保存原始文本内容（未转换为HTML的版本）
  
  // ========== 参数设置 ==========
  const [parameters, setParameters] = useState({
    temperature: 0.7,
    maxTokens: 2000,
    topP: 0.9,
    stream: true
  });
  
  // ========== 弹窗控制 ==========
  const [promptLibraryVisible, setPromptLibraryVisible] = useState(false);
  const [promptEditorVisible, setPromptEditorVisible] = useState(false);
  const [modelComparisonVisible, setModelComparisonVisible] = useState(false);
  const [debugPanelVisible, setDebugPanelVisible] = useState(false);
  const [optimizationVisible, setOptimizationVisible] = useState(false);
  const [parameterVisible, setParameterVisible] = useState(false);
  const [customFormatVisible, setCustomFormatVisible] = useState(false);
  const [customFormatInput, setCustomFormatInput] = useState('');
  const [refineDrawerVisible, setRefineDrawerVisible] = useState(false);  // 新增：微调抽屉
  
  // ========== Refs ==========
  const generationAbortController = useRef<AbortController>();
  const progressIntervalRef = useRef<NodeJS.Timeout>();
  
  // ========== 计算属性 ==========
  const isFavorited = item && favoriteIds.includes(item.item_id);
  const platformInfo = item && platformConfig[item.platform];

  // 只显示激活且健康的模型（过滤掉unhealthy状态）
  let availableModels = configs.filter(c => {
    const isActive = c.isActive;
    const isHealthy = c.status === 'healthy' || c.status === 'warning';
    return isActive && isHealthy;
  });

  // 按状态排序：healthy > warning
  availableModels.sort((a, b) => {
    const statusPriority = { healthy: 3, warning: 2, unhealthy: 1, unknown: 0 };
    const priorityA = statusPriority[a.status] || 0;
    const priorityB = statusPriority[b.status] || 0;
    return priorityB - priorityA;
  });

  console.log('📋 [HotCreatorModal] 模型过滤详情:', {
    total: configs.length,
    filtered: availableModels.length,
    allConfigs: configs.map(c => ({
      id: c.id,
      name: c.displayName || c.modelName,
      isActive: c.isActive,
      status: c.status,
      included: c.isActive && (c.status === 'healthy' || c.status === 'warning')
    })),
    availableModels: availableModels.map(m => ({
      name: m.displayName || m.modelName,
      status: m.status
    }))
  });

  // 移动端调试信息 - 在configs变化时也输出
  useEffect(() => {
    if (isMobile) {
      console.log('📱 移动端模型配置调试 [configs变化]:', {
        visible,
        totalConfigs: configs.length,
        availableModels: availableModels.length,
        rawConfigs: configs.map(c => ({
          id: c.id,
          name: c.displayName || c.modelName,
          isActive: c.isActive,
          status: c.status
        })),
        filteredModels: availableModels.map(m => ({
          name: m.displayName || m.modelName,
          status: m.status
        }))
      });
    }
  }, [configs, visible, isMobile]); // 依赖configs，实时监控数据变化

  // ========== 快速预设配置 ==========
  const quickRefineOptions = {
    // 基础优化 - 这些是微调操作
    basic: [
      { key: 'concise', label: '更简洁', icon: '📝', prompt: '请将内容改得更简洁，删除冗余表述，保留核心观点', isRegenerate: false },
      { key: 'formal', label: '更正式', icon: '🎩', prompt: '请调整为更正式、专业的语气和表达方式', isRegenerate: false },
      { key: 'casual', label: '更轻松', icon: '😊', prompt: '请调整为更轻松、易懂的语气，增加可读性', isRegenerate: false },
      { key: 'data', label: '增加数据', icon: '📊', prompt: '请在合适的地方增加具体的数据和统计信息来支撑观点', isRegenerate: false },
      { key: 'case', label: '增加案例', icon: '💡', prompt: '请添加具体的案例或实例来说明观点', isRegenerate: false },
      { key: 'restructure', label: '重新组织', icon: '🔄', prompt: '请重新组织内容结构，使逻辑更清晰、层次更分明', isRegenerate: false },
    ],
    // 新闻舆情专用 - 这些是重新生成操作（改变核心角度）
    newsOpinion: [
      { key: 'newsAngle', label: '新闻角度', icon: '📰', prompt: '请以新闻报道的客观角度重写，突出5W1H要素（何时、何地、何人、何事、为何、如何）', isRegenerate: true },
      { key: 'opinionAnalysis', label: '舆情分析', icon: '📢', prompt: '请从舆情分析的角度重新创作，总结各方观点、情感倾向和舆论走向', isRegenerate: true },
      { key: 'viewpointHighlight', label: '观点突出', icon: '🎯', prompt: '请以鲜明观点为主导重新创作，使论点更加有力', isRegenerate: true },
      { key: 'objectiveNeutral', label: '客观中立', icon: '⚖️', prompt: '请以客观中立的立场重新创作，避免主观判断和情绪化表达', isRegenerate: true },
      { key: 'hotspotFocus', label: '热点聚焦', icon: '🔥', prompt: '请重新创作，聚焦热点话题的核心信息，突出事件的社会影响和讨论焦点', isRegenerate: true },
      { key: 'deepInterpretation', label: '深度解读', icon: '📖', prompt: '请重新创作深度分析文章，增加背景信息，挖掘事件背后的深层原因和影响', isRegenerate: true },
    ],
    // 格式调整 - 格式调整属于微调，不是重新生成
    format: [
      { key: 'officialDoc', label: '公文格式', icon: '📄', isRegenerate: false, prompt: `请按照标准公文格式重新输出，确保复制到Word时格式保持一致：

【格式要求】
1. 标题：黑体三号，居中，加粗，段前段后空1行
2. 主送机关：仿宋GB-2312小四号，顶格
3. 正文：仿宋GB-2312小四号，两端对齐，首行缩进两个字符
4. 附件说明：仿宋GB-2312小四号（如有）
5. 发文机关署名：仿宋GB-2312小四号，右对齐
6. 成文日期：仿宋GB-2312小四号，右对齐

【要求】保持原有内容不变，仅调整为标准公文格式。` },
      { key: 'reportFormat', label: '报告格式', icon: '📋', isRegenerate: false, prompt: `请按照标准报告格式重新输出，确保复制到Word时格式保持一致：

【格式要求】
1. 报告标题：黑体二号，居中，加粗
2. 一级标题：黑体三号，段前段后空1行，左对齐
3. 二级标题：黑体四号，段前段后空0.5行，左对齐
4. 正文：仿宋GB-2312小四号，两端对齐，首行缩进两个字符
5. 摘要/前言：楷体，小四号
6. 结论/建议：单独成段，加粗

【结构】包含报告标题、摘要/前言、正文（分段明确，使用序号）、结论/建议、附录（如需要）` },
      { key: 'newsFormat', label: '新闻稿格式', icon: '📰', isRegenerate: false, prompt: `请按照新闻稿格式重新输出，确保复制到Word时格式保持一致：

【格式要求】
1. 新闻标题：黑体二号，居中，加粗
2. 副标题：楷体三号，居中（如有）
3. 导语：仿宋GB-2312小四号，加粗，首行缩进
4. 正文：仿宋GB-2312小四号，两端对齐，首行缩进两个字符
5. 背景资料：楷体小四号，单独成段

【结构】采用倒金字塔结构，突出5W1H要素（何时、何地、何人、何事、为何、如何）` },
      { key: 'customFormat', label: '自定义格式', icon: '⚙️', isRegenerate: false, prompt: '请保持内容不变，根据以下格式要求重新输出：', isCustom: true },
    ]
  };

  // ========== 生命周期 ==========
  // 预加载模型配置（页面初始化时就加载，不等modal打开）
  useEffect(() => {
    // 只在第一次加载时执行
    if (configs.length === 0) {
      console.log('🔄 预加载模型配置...');
      loadConfigs().then(() => {
        console.log('✅ 模型配置预加载完成');
      }).catch(err => {
        console.error('❌ 模型配置预加载失败:', err);
      });
    }
  }, []); // 空依赖，只执行一次

  useEffect(() => {
    if (visible && item) {
      // Modal打开时强制重新加载配置，确保获取最新数据
      console.log('🔄 Modal打开，重新加载模型配置...');
      loadConfigs().then(() => {
        console.log('✅ 模型配置重新加载完成, configs:', configs.length);
      });

      // 只在创作tab时才加载详情数据，查看tab才需要
      if (defaultTab === 'detail') {
        fetchDetailData();
      }
      initializeCreation();
      loadPrompts();
      setActiveTab(defaultTab);
    }
  }, [visible, item, defaultTab]);
  
  // 清理定时器
  useEffect(() => {
    return () => {
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
      }
    };
  }, []);

  // 自动选择第一个可用模型
  useEffect(() => {
    if (!selectedModel && availableModels.length > 0) {
      setSelectedModel(availableModels[0].id);
    }
  }, [availableModels, selectedModel]);
  
  // ========== 数据获取 ==========
  const fetchDetailData = async () => {
    if (!item) return;
    
    setLoading(true);
    try {
      const data = await hotRadarService.getHotItemDetail(item.item_id, item.platform);
      setDetailData(data);
    } catch (error) {
      message.error('获取详情数据失败');
    } finally {
      setLoading(false);
    }
  };
  
  // ========== 初始化创作 ==========
  const initializeCreation = () => {
    if (!item) return;
    
    // 设置标题
    setTitle(`基于热点话题: ${item.title}`);
    
    // 生成初始提示词
    const initialPrompt = `请基于以下热点话题进行创作：

热点标题：${item.title}
平台来源：${platformInfo?.name || item.platform}
热度排名：#${item.rank}
话题摘要：${item.excerpt || ''}

创作要求：
1. 深入分析热点背后的原因和影响
2. 提供独特的观点和见解
3. 内容要有深度，避免表面化
4. 适当引用相关数据和事例
5. 保持客观公正，多角度分析

请开始创作...`;

    setContent(initialPrompt);
  };
  
  // ========== 创作功能 ==========
  const handleGenerate = async () => {
    if (!selectedModel) {
      message.warning('请先选择AI模型');
      return;
    }
    if (!content.trim()) {
      message.warning('请输入创作内容');
      return;
    }

    // 检查选中的模型配置
    const modelConfig = configs.find(c => c.id === selectedModel);
    if (!modelConfig) {
      message.error('未找到模型配置');
      return;
    }

    try {
      // 设置生成状态
      setLocalGenerating(true);
      setGenerateProgress(0);
      setGenerateStatus('正在准备...');
      generationAbortController.current = new AbortController();

      // 模拟进度更新
      progressIntervalRef.current = setInterval(() => {
        setGenerateProgress(prev => {
          if (prev >= 90) {
            if (progressIntervalRef.current) {
              clearInterval(progressIntervalRef.current);
            }
            return 90;
          }
          return prev + 10;
        });
      }, 300);
      
      // 构建消息列表
      const messages = [];
      
      // 添加系统提示词
      if (currentPrompt?.systemPrompt) {
        messages.push({
          role: 'system' as const,
          content: currentPrompt.systemPrompt
        });
      }
      
      // 构建用户消息
      let userContent = content;
      
      // 添加热点相关信息
      if (detailData?.comments && detailData.comments.length > 0) {
        const topComments = detailData.comments.slice(0, 3).map(c => c.content).join('\n');
        userContent += `\n\n热门评论参考：\n${topComments}`;
      }
      
      messages.push({
        role: 'user' as const,
        content: userContent
      });
      
      // 获取选中的模型配置
      const modelConfig = configs.find(c => c.id === selectedModel)
      if (!modelConfig) {
        message.error('未找到模型配置')
        return
      }
      
      // 使用流式生成
      if (parameters.stream) {
        // 目前暂不支持流式生成，使用普通生成
        message.info('流式生成暂不可用，切换为普通生成')
      }

      // 更新进度状态
      setGenerateStatus('正在调用AI模型...');

      // 使用热点创作专用的LangChain生成
      const result = await aiGenerationService.generateHotContent(
        item.item_id,
        item.platform,
        'news_report', // 默认写作角度，可以后续添加选择器
        userContent,
        modelConfig.modelName || 'gpt-3.5-turbo',
        {
          temperature: parameters.temperature,
          maxTokens: parameters.maxTokens,
          topP: parameters.topP
        },
        {
          provider: modelConfig.provider,
          apiKey: modelConfig.apiKey,
          apiBase: modelConfig.baseUrl
        }
      )

      // 清除进度定时器
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
      }

      // 完成进度
      setGenerateProgress(100);
      setGenerateStatus('生成完成');

      console.log('=== 生成结果 ===');
      console.log('result对象:', result);
      console.log('result.content类型:', typeof result.content);
      console.log('result.content长度:', result.content?.length);
      console.log('result.content内容（前200字符）:', result.content?.substring(0, 200));

      // 将Markdown转换为HTML（简单转换）
      let htmlContent = result.content
        // 标题转换
        .replace(/^### (.*$)/gm, '<h3>$1</h3>')
        .replace(/^## (.*$)/gm, '<h2>$1</h2>')
        .replace(/^# (.*$)/gm, '<h1>$1</h1>')
        // 加粗
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        // 斜体
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        // 换行
        .replace(/\n\n/g, '</p><p>')
        .replace(/\n/g, '<br/>');

      // 包裹在段落标签中
      htmlContent = '<p>' + htmlContent + '</p>';

      console.log('转换后的HTML（前200字符）:', htmlContent.substring(0, 200));

      setGeneratedContent(htmlContent);
      setRawContent(result.content); // 保存原始文本
      console.log('已调用setGeneratedContent和setRawContent');

      // 初始化版本0
      const initialVersion = {
        version: 0,
        content: result.content,
        timestamp: new Date().toLocaleString('zh-CN')
      };
      setContentVersions([initialVersion]);
      setCurrentVersion(0);

      // 解析段落用于后续选择组合 - 使用原始文本
      parseParagraphs(result.content);

      checkContentQuality(result.content);
      message.success('内容生成完成！');
    } catch (error: any) {
      // 清除进度定时器
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
      }

      if (error.name === 'AbortError') {
        message.info('生成已取消');
        setGenerateStatus('已取消');
      } else {
        message.error('生成失败：' + error.message);
        setGenerateStatus('生成失败');
      }
    } finally {
      // 重置生成状态
      setLocalGenerating(false);
      setTimeout(() => {
        setGenerateProgress(0);
        setGenerateStatus('');
      }, 2000);
    }
  };
  
  // 停止生成
  const handleStopGeneration = () => {
    if (generationAbortController.current) {
      generationAbortController.current.abort();
    }
  };

  // ========== 微调功能 ==========

  // 快速预设微调
  const handleQuickRefine = async (option: any) => {
    if (!generatedContent) {
      message.warning('请先生成内容');
      return;
    }

    // 弹出编辑框让用户确认或修改prompt
    Modal.confirm({
      title: `${option.icon} ${option.label}`,
      width: 600,
      content: (
        <div>
          <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
            {option.isRegenerate ? '将重新生成内容' : '将微调优化内容'}
          </Text>
          <TextArea
            id="refine-prompt-edit"
            defaultValue={option.prompt}
            rows={6}
            placeholder="编辑优化要求..."
            style={{ marginTop: 8 }}
          />
          <Text type="secondary" style={{ display: 'block', marginTop: 8, fontSize: 12 }}>
            💡 提示：您可以修改上面的要求，让AI更精确地按您的需求进行{option.isRegenerate ? '重新生成' : '优化'}
          </Text>
        </div>
      ),
      okText: option.isRegenerate ? '重新生成' : '开始优化',
      cancelText: '取消',
      onOk: async () => {
        const textarea = document.getElementById('refine-prompt-edit') as HTMLTextAreaElement;
        const editedPrompt = textarea?.value || option.prompt;
        await handleRefine(editedPrompt, option.isRegenerate);
      }
    });
  };

  // 处理自定义格式
  const handleCustomFormat = () => {
    if (!generatedContent) {
      message.warning('请先生成内容');
      return;
    }

    // 设置默认格式要求
    const defaultFormat = `一级标题：黑体，三号(16pt)，段前段后空1行，左对齐
二级标题：黑体，四号(14pt)，段前段后空0.5行，左对齐
正文：仿宋GB-2312，小四号(12pt)，两端对齐，首行缩进两个字符`;

    setCustomFormatInput(defaultFormat);
    setCustomFormatVisible(true);
  };

  // 应用自定义格式
  const handleApplyCustomFormat = async () => {
    if (!customFormatInput.trim()) {
      message.warning('请输入格式要求');
      return;
    }

    const formatPrompt = `请保持内容不变，根据以下格式要求重新输出：\n\n${customFormatInput}\n\n注意：输出格式应能在复制到Word文档时保持格式。`;

    setCustomFormatVisible(false);
    await handleRefine(formatPrompt);
  };

  // 自定义微调
  const handleCustomRefine = async () => {
    if (!refineInput.trim()) {
      message.warning('请输入微调要求');
      return;
    }
    if (!generatedContent) {
      message.warning('请先生成内容');
      return;
    }

    await handleRefine(refineInput);
    setRefineInput(''); // 清空输入框
  };

  // 执行微调
  const handleRefine = async (requirement: string, isRegenerate: boolean = false) => {
    if (!selectedModel) {
      message.warning('请先选择AI模型');
      return;
    }

    try {
      setIsRefining(true);

      // 获取模型配置
      const modelConfig = configs.find(c => c.id === selectedModel);
      if (!modelConfig) {
        message.error('未找到模型配置');
        return;
      }

      // 构建微调Prompt - 根据是否重新生成使用不同的提示
      let refinePrompt;
      if (isRegenerate) {
        // 重新生成：完全按新要求生成
        refinePrompt = `请根据以下要求重新生成内容：

${requirement}

原始内容作为参考：
${generatedContent}

请重新创作，生成全新的内容。`;
      } else {
        // 微调：在原有基础上优化
        refinePrompt = `请根据以下要求对内容进行微调优化：

${requirement}

原始内容：
${generatedContent}

请直接输出微调后的内容，保持原有格式。`;
      }

      // 调用AI进行微调
      const result = await aiGenerationService.generateHotContent(
        item.item_id,
        item.platform,
        'news_report',
        refinePrompt,
        modelConfig.modelName || 'gpt-3.5-turbo',
        {
          temperature: 0.7,
          maxTokens: 2000,
          topP: 0.9
        },
        {
          provider: modelConfig.provider,
          apiKey: modelConfig.apiKey,
          apiBase: modelConfig.baseUrl
        }
      );

      // 保存到历史 - 记录是微调还是重新生成
      const historyItem = {
        timestamp: new Date().toLocaleString('zh-CN'),
        requirement: isRegenerate ? `[重新生成] ${requirement}` : requirement,
        beforeContent: generatedContent,
        afterContent: result.content
      };
      setRefineHistory(prev => [historyItem, ...prev]);

      // 保存版本
      const newVersion = {
        version: currentVersion + 1,
        content: result.content,
        timestamp: new Date().toLocaleString('zh-CN')
      };
      setContentVersions(prev => [...prev, newVersion]);
      setCurrentVersion(newVersion.version);

      // 更新生成内容 - 转换为HTML
      let htmlContent = result.content
        .replace(/^### (.*$)/gm, '<h3>$1</h3>')
        .replace(/^## (.*$)/gm, '<h2>$1</h2>')
        .replace(/^# (.*$)/gm, '<h1>$1</h1>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/\n\n/g, '</p><p>')
        .replace(/\n/g, '<br/>');
      htmlContent = '<p>' + htmlContent + '</p>';

      setGeneratedContent(htmlContent);
      setRawContent(result.content); // 保存原始文本

      // 重新解析段落
      parseParagraphs(result.content);

      message.success(isRegenerate ? '内容已重新生成！' : '微调完成！');
    } catch (error: any) {
      message.error((isRegenerate ? '重新生成' : '微调') + '失败：' + error.message);
    } finally {
      setIsRefining(false);
    }
  };

  // 版本回退
  const handleVersionRollback = (version: number) => {
    const targetVersion = contentVersions.find(v => v.version === version);
    if (targetVersion) {
      // 转换为HTML
      let htmlContent = targetVersion.content
        .replace(/^### (.*$)/gm, '<h3>$1</h3>')
        .replace(/^## (.*$)/gm, '<h2>$1</h2>')
        .replace(/^# (.*$)/gm, '<h1>$1</h1>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/\n\n/g, '</p><p>')
        .replace(/\n/g, '<br/>');
      htmlContent = '<p>' + htmlContent + '</p>';

      setGeneratedContent(htmlContent);
      setRawContent(targetVersion.content); // 更新原始文本
      setCurrentVersion(version);
      // 重新解析段落
      parseParagraphs(targetVersion.content);
      message.success(`已回退到版本 ${version}`);
    }
  };

  // ========== 段落选择和组合功能 ==========

  // 解析生成内容为段落
  const parseParagraphs = (content: string) => {
    // 按双换行符或标题分割段落
    const paragraphs = content
      .split(/\n\n+/)
      .map((p) => p.trim())
      .filter((p) => p.length > 0)
      .map((p, index) => ({
        id: `para-${index}`,
        content: p,
        selected: true // 默认全选
      }));

    setContentParagraphs(paragraphs);
  };

  // 切换段落选择状态
  const toggleParagraphSelection = (id: string) => {
    setContentParagraphs(prev =>
      prev.map(p => p.id === id ? { ...p, selected: !p.selected } : p)
    );
  };

  // 全选/取消全选
  const toggleAllParagraphs = (selected: boolean) => {
    setContentParagraphs(prev =>
      prev.map(p => ({ ...p, selected }))
    );
  };

  // 组合选中的段落
  const composeArticle = () => {
    const selectedParagraphs = contentParagraphs
      .filter(p => p.selected)
      .map(p => p.content);

    if (selectedParagraphs.length === 0) {
      message.warning('请至少选择一个段落');
      return;
    }

    // 组合段落文本
    const composedText = selectedParagraphs.join('\n\n');
    setComposedArticle(composedText);
    setRawContent(composedText); // 更新原始文本

    // 转换为HTML格式（与生成时的格式保持一致）
    let htmlContent = composedText
      // 标题转换
      .replace(/^### (.*$)/gm, '<h3>$1</h3>')
      .replace(/^## (.*$)/gm, '<h2>$1</h2>')
      .replace(/^# (.*$)/gm, '<h1>$1</h1>')
      // 加粗
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      // 斜体
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      // 换行
      .replace(/\n\n/g, '</p><p>')
      .replace(/\n/g, '<br/>');

    // 包裹在段落标签中
    htmlContent = '<p>' + htmlContent + '</p>';

    setGeneratedContent(htmlContent);
    setShowParagraphSelector(false);

    // 更新版本历史
    const newVersion = {
      version: currentVersion + 1,
      content: composedText,
      timestamp: new Date().toLocaleString('zh-CN')
    };
    setContentVersions(prev => [...prev, newVersion]);
    setCurrentVersion(newVersion.version);

    console.log('✅ [段落组合] 已组合段落:', selectedParagraphs.length, '个');
    console.log('📝 [段落组合] 原始文本长度:', composedText.length);
    console.log('🎨 [段落组合] HTML长度:', htmlContent.length);

    message.success(`已组合 ${selectedParagraphs.length} 个段落，内容已更新到编辑器`);
  };

  // 打开段落选择器
  const openParagraphSelector = () => {
    if (contentParagraphs.length === 0) {
      // 如果还没有解析段落，先解析
      console.log('📝 [段落选择器] 开始解析段落，rawContent长度:', rawContent.length);
      if (rawContent) {
        parseParagraphs(rawContent);
      } else {
        message.warning('没有可用的内容进行段落选择');
        return;
      }
    } else {
      console.log('📝 [段落选择器] 已有段落数据:', contentParagraphs.length);
    }
    setShowParagraphSelector(true);
  };

  // 检查内容质量
  const checkContentQuality = async (text: string) => {
    try {
      // 调用质量评估服务
      const qualityResult = await qualityService.evaluateQuality({
        content: text,
        scenario: 'general',
        language: 'zh'
      });
      
      setQualityScore(Math.round(qualityResult.overall_score * 100));
      
      // 调用原创性检查服务
      const originalityResult = await qualityService.checkOriginality({
        content: text,
        check_internet: true,
        check_database: true
      });
      
      setOriginalityScore(Math.round(originalityResult.originality_score * 100));
    } catch (error) {
      console.error('Quality check error:', error);
      // 如果API调用失败，使用模拟数据
      setQualityScore(Math.floor(Math.random() * 20) + 75);
      setOriginalityScore(Math.floor(Math.random() * 15) + 80);
    }
  };
  
  // 处理提示词选择
  const handlePromptSelect = (template: any) => {
    selectPrompt(template.id);
    
    // 结合热点信息生成提示词
    let processedPrompt = template.systemPrompt;
    if (item) {
      processedPrompt = processedPrompt.replace('{topic}', item.title);
      processedPrompt = processedPrompt.replace('{platform}', platformInfo?.name || item.platform);
    }
    
    setContent(processedPrompt);
    setPromptLibraryVisible(false);
    message.success(`已应用提示词模板: ${template.name}`);
  };
  
  // 处理多模型对比
  const handleModelComparison = () => {
    if (!content.trim()) {
      message.warning('请先输入创作内容');
      return;
    }
    setModelComparisonVisible(true);
  };

  // 处理调试面板
  const handleDebugPanel = () => {
    setDebugPanelVisible(true);
  };
  
  // 应用优化建议
  const handleApplyOptimization = async (optimizedContent?: string) => {
    if (optimizedContent) {
      setGeneratedContent(optimizedContent);
      setOptimizationVisible(false);
      message.success('已应用优化建议');
    } else if (generatedContent) {
      try {
        // 调用优化服务
        const result = await optimizationService.optimize({
          content: generatedContent,
          optimization_type: 'all',
          target_style: 'formal',
          language: 'zh',
          preserve_tone: true
        });
        
        setGeneratedContent(result.optimized_content);
        checkContentQuality(result.optimized_content);
        message.success(`优化完成：修复${result.improvements.grammar_fixes}个语法错误，改进${result.improvements.style_improvements}个风格问题`);
      } catch (error) {
        console.error('Optimization error:', error);
        message.error('优化失败');
      }
    }
  };
  
  // 导出内容
  const handleExport = (format: string) => {
    if (!generatedContent) {
      message.warning('没有可导出的内容');
      return;
    }
    message.info(`正在导出为 ${format.toUpperCase()} 格式...`);
  };
  
  // ========== UI辅助函数 ==========
  const handleFavorite = () => {
    if (item) {
      toggleFavorite(item.item_id);
    }
  };
  
  const handleOpenSource = () => {
    if (item?.url) {
      window.open(item.url, '_blank');
    }
  };
  
  // 工具菜单
  const toolsMenu = (
    <Menu>
      <Menu.ItemGroup title="提示词工具">
        <Menu.Item 
          key="prompt-library" 
          icon={<BookOutlined />}
          onClick={() => setPromptLibraryVisible(true)}
        >
          提示词库
        </Menu.Item>
        <Menu.Item 
          key="prompt-editor" 
          icon={<EditOutlined />}
          onClick={() => setPromptEditorVisible(true)}
        >
          编辑提示词
        </Menu.Item>
      </Menu.ItemGroup>
      
      <Menu.Divider />
      
      <Menu.ItemGroup title="生成增强">
        <Menu.Item 
          key="model-comparison" 
          icon={<SwapOutlined />}
          onClick={handleModelComparison}
        >
          多模型对比
        </Menu.Item>
        <Menu.Item 
          key="parameters" 
          icon={<SettingOutlined />}
          onClick={() => setParameterVisible(true)}
        >
          参数设置
        </Menu.Item>
      </Menu.ItemGroup>
      
      <Menu.Divider />
      
      <Menu.ItemGroup title="内容优化">
        <Menu.Item 
          key="optimization" 
          icon={<BulbOutlined />}
          onClick={() => setOptimizationVisible(true)}
          disabled={!generatedContent}
        >
          优化建议
        </Menu.Item>
        <Menu.Item 
          key="quality" 
          icon={<SafetyCertificateOutlined />}
          onClick={() => checkContentQuality(generatedContent)}
          disabled={!generatedContent}
        >
          质量检测
        </Menu.Item>
      </Menu.ItemGroup>
    </Menu>
  );
  
  // 导出菜单
  const exportMenu = (
    <Menu onClick={(e) => handleExport(e.key)}>
      <Menu.Item key="md">Markdown</Menu.Item>
      <Menu.Item key="html">HTML</Menu.Item>
      <Menu.Item key="docx">Word</Menu.Item>
      <Menu.Item key="pdf">PDF</Menu.Item>
    </Menu>
  );
  
  // 渲染评论
  const renderComments = (comments: Comment[] = []) => (
    <List
      className="comment-list"
      itemLayout="horizontal"
      dataSource={comments.slice(0, 5)}
      renderItem={(comment) => (
        <List.Item>
          <List.Item.Meta
            avatar={<Avatar>{comment.author[0]}</Avatar>}
            title={
              <Space>
                <Text strong>{comment.author}</Text>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  {new Date(comment.created_at).toLocaleString('zh-CN')}
                </Text>
              </Space>
            }
            description={
              <>
                <Paragraph>{comment.content}</Paragraph>
                <Space>
                  <Button size="small" type="text" icon={<LikeOutlined />}>
                    {comment.like_count}
                  </Button>
                  <Button
                    size="small"
                    type="text"
                    icon={<CopyOutlined />}
                    onClick={() => {
                      setContent(prev => `${prev}\n\n参考评论：${comment.content}`);
                      message.success('已添加到创作内容');
                    }}
                  >
                    引用
                  </Button>
                </Space>
              </>
            }
          />
        </List.Item>
      )}
    />
  );
  
  if (!item) return null;
  
  return (
    <Modal
      title={
        <div className="modal-header">
          <Space>
            <FireOutlined style={{ color: '#ff4d4f' }} />
            <Text strong>热点创作工作台</Text>
            <Tag color={platformInfo?.color}>
              {platformInfo?.icon} {platformInfo?.name}
            </Tag>
            <Tag color="red">热度 #{item.rank}</Tag>
          </Space>
        </div>
      }
      open={visible}
      onCancel={onClose}
      width={isMobile ? '100%' : '90%'}
      style={isMobile ? { top: 0, margin: 0, padding: 0, maxWidth: 'none' } : { top: 20, maxWidth: 1600 }}
      footer={null}
      bodyStyle={{ padding: 0, height: isMobile ? '100vh' : '85vh', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}
    >
      <Spin spinning={loading} style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div className="hot-creator-modal-content" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
            className="full-height-tabs"
            tabBarExtraContent={
              <Space>
                <Button
                  icon={isFavorited ? <StarFilled /> : <StarOutlined />}
                  onClick={handleFavorite}
                >
                  {isFavorited ? '已收藏' : '收藏'}
                </Button>
                <Button icon={<LinkOutlined />} onClick={handleOpenSource}>
                  查看原文
                </Button>
              </Space>
            }
          >
            {/* 创作标签页 */}
            <TabPane 
              tab={
                <Space>
                  <EditOutlined />
                  AI创作
                </Space>
              } 
              key="create"
            >
              <div style={{
                padding: isMobile ? '8px' : '12px',
                height: isMobile ? 'calc(100vh - 100px)' : 'calc(85vh - 80px)',
                overflowY: 'auto',
                display: 'flex',
                flexDirection: 'column'
              }}>
                {/* 热点信息卡片 - 缩小高度 */}
                <Card size="small" style={{
                  marginBottom: isMobile ? 8 : 12,
                  padding: isMobile ? '2px 6px' : '4px 8px',
                  flexShrink: 0
                }}>
                  <Title level={5} style={{
                    margin: 0,
                    fontSize: isMobile ? 11 : 13
                  }}>{item.title}</Title>
                  {item.excerpt && (
                    <Paragraph
                      ellipsis={{ rows: 1, expandable: false }}
                      style={{
                        marginTop: isMobile ? 2 : 4,
                        marginBottom: 0,
                        fontSize: isMobile ? 10 : 11
                      }}
                    >
                      {item.excerpt}
                    </Paragraph>
                  )}
                </Card>

                {/* 创作区域 - 使用flex自动填充剩余空间 */}
                <Row gutter={isMobile ? 8 : 12} style={{ flex: 1, minHeight: 0 }}>
                  {/* 左侧：输入区 */}
                  <Col span={isMobile ? 24 : 12} style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                    <Card
                      title={
                        <Space>
                          <Text>创作输入</Text>
                          {currentPrompt && (
                            <Tag color="green">{currentPrompt.name}</Tag>
                          )}
                        </Space>
                      }
                      extra={
                        <Space>
                          <PromptSelector
                            onSelect={handlePromptSelect}
                            showQuickActions={false}
                          />
                          <Dropdown overlay={toolsMenu}>
                            <Button icon={<ThunderboltOutlined />}>
                              工具箱
                            </Button>
                          </Dropdown>
                        </Space>
                      }
                      style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
                      bodyStyle={{ flex: 1, padding: isMobile ? '8px' : '12px', display: 'flex', flexDirection: 'column', minHeight: 0 }}
                    >
                      {availableModels.length > 0 ? (
                        <>
                          <Select
                            value={selectedModel}
                            onChange={setSelectedModel}
                            style={{ width: '100%', marginBottom: 12 }}
                            placeholder="选择AI模型"
                          >
                            {availableModels.map(config => (
                              <Option key={config.id} value={config.id}>
                                <Space>
                                  <ModelStatusIndicator status={config.status} />
                                  {config.displayName || config.modelName}
                                </Space>
                              </Option>
                            ))}
                          </Select>
                        </>
                      ) : (
                        <div style={{
                          padding: isMobile ? '16px 12px' : '12px',
                          background: '#fff7e6',
                          border: '1px solid #ffd591',
                          borderRadius: '4px',
                          marginBottom: 12,
                          textAlign: 'center'
                        }}>
                          <p style={{ margin: 0, color: '#d46b08', fontSize: isMobile ? 14 : 13 }}>
                            ⚠️ 暂无可用模型
                          </p>
                          <p style={{ margin: '8px 0', fontSize: isMobile ? 13 : 12, color: '#ad6800' }}>
                            需要先配置AI模型才能开始创作
                          </p>
                          <Button
                            type="primary"
                            size={isMobile ? 'middle' : 'small'}
                            onClick={() => {
                              window.open('/model-config', '_blank');
                            }}
                            style={{ marginTop: 4 }}
                          >
                            前往配置模型
                          </Button>
                        </div>
                      )}

                      <TextArea
                        value={content}
                        onChange={(e) => setContent(e.target.value)}
                        placeholder="输入创作提示词..."
                        style={{ flex: 1, resize: 'none', minHeight: 200 }}
                      />

                      <div style={{ marginTop: 12, flexShrink: 0 }}>
                        {localGenerating ? (
                          <>
                            <Button
                              danger
                              block
                              onClick={handleStopGeneration}
                            >
                              停止生成
                            </Button>
                            {/* 生成进度条 - 移动端加强显示 */}
                            <div style={{
                              marginTop: 12,
                              padding: isMobile ? '12px' : '8px',
                              background: '#f5f5f5',
                              borderRadius: '4px'
                            }}>
                              <Progress
                                percent={generateProgress}
                                status={generateProgress === 100 ? 'success' : 'active'}
                                strokeColor={{
                                  '0%': '#108ee9',
                                  '100%': '#87d068',
                                }}
                                strokeWidth={isMobile ? 8 : 6}
                              />
                              {generateStatus && (
                                <Text type="secondary" style={{
                                  fontSize: isMobile ? 13 : 12,
                                  marginTop: 8,
                                  display: 'block',
                                  textAlign: 'center'
                                }}>
                                  {generateStatus}
                                </Text>
                              )}
                            </div>
                          </>
                        ) : (
                          <Button
                            type="primary"
                            block
                            icon={<SendOutlined />}
                            onClick={handleGenerate}
                            disabled={!content.trim() || !selectedModel}
                            loading={localGenerating}
                          >
                            开始生成
                          </Button>
                        )}
                      </div>
                    </Card>
                  </Col>

                  {/* 右侧：生成区 */}
                  <Col span={isMobile ? 24 : 12} style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                    <Card
                      title={
                        <Space>
                          <Text>生成内容</Text>
                          {localGenerating && <Spin size="small" />}
                        </Space>
                      }
                      extra={
                        <Space>
                          {generatedContent && (
                            <>
                              <Button
                                size="small"
                                icon={<FileTextOutlined />}
                                onClick={openParagraphSelector}
                                title="选择段落组合文章"
                              >
                                组合
                              </Button>
                              <Button
                                size="small"
                                icon={<EditOutlined />}
                                onClick={() => setRefineDrawerVisible(true)}
                              >
                                微调
                              </Button>
                              <Button
                                size="small"
                                icon={<BulbOutlined />}
                                onClick={() => setOptimizationVisible(true)}
                              >
                                优化
                              </Button>
                              <Button
                                size="small"
                                icon={<CopyOutlined />}
                                onClick={() => {
                                  navigator.clipboard.writeText(generatedContent);
                                  message.success('已复制');
                                }}
                              >
                                复制
                              </Button>
                              <Dropdown overlay={exportMenu}>
                                <Button size="small" icon={<DownloadOutlined />}>
                                  导出
                                </Button>
                              </Dropdown>
                            </>
                          )}
                        </Space>
                      }
                      style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
                      bodyStyle={{ flex: 1, padding: isMobile ? '8px' : '12px', display: 'flex', flexDirection: 'column', minHeight: 0 }}
                    >
                      {/* 质量评分 - 固定高度 */}
                      {(qualityScore || originalityScore) && (
                        <div style={{ marginBottom: 8, flexShrink: 0 }}>
                          <Space direction="horizontal" style={{ width: '100%', justifyContent: 'space-around' }} size="middle">
                            {qualityScore && (
                              <div style={{ flex: 1 }}>
                                <Text type="secondary" style={{ fontSize: 12 }}>质量: {qualityScore}%</Text>
                                <Progress
                                  percent={qualityScore}
                                  status={qualityScore >= 80 ? 'success' : 'normal'}
                                  showInfo={false}
                                  strokeWidth={6}
                                />
                              </div>
                            )}
                            {originalityScore && (
                              <div style={{ flex: 1 }}>
                                <Text type="secondary" style={{ fontSize: 12 }}>原创: {originalityScore}%</Text>
                                <Progress
                                  percent={originalityScore}
                                  status={originalityScore >= 80 ? 'success' : 'normal'}
                                  showInfo={false}
                                  strokeWidth={6}
                                />
                              </div>
                            )}
                          </Space>
                        </div>
                      )}

                      {/* 生成内容展示区 - 使用flex填充剩余空间 */}
                      <div style={{ flex: 1, minHeight: 300, display: 'flex', flexDirection: 'column' }}>
                        <RichTextEditor
                          value={generatedContent}
                          onChange={setGeneratedContent}
                          placeholder="AI生成的内容将显示在这里..."
                          height="100%"
                          isMobile={isMobile}
                          readOnly={false}
                        />
                      </div>
                    </Card>
                  </Col>
                </Row>

                {/* 微调面板 - 改为抽屉，不占用主要空间 */}
                {generatedContent && false && (
                  <Card
                    title="内容微调"
                    style={{ marginTop: isMobile ? 8 : 12 }}
                    size="small"
                    bodyStyle={{ padding: isMobile ? '8px' : '12px' }}
                  >
                    <Space direction="vertical" style={{ width: '100%' }} size="small">
                      {/* 快速优化按钮 */}
                      <div>
                        <Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>基础优化：</Text>
                        <Space wrap size="small">
                          {quickRefineOptions.basic.map(option => (
                            <Button
                              key={option.key}
                              size="small"
                              onClick={() => handleQuickRefine(option)}
                              loading={isRefining}
                              disabled={isRefining}
                            >
                              <span>{option.icon} {option.label}</span>
                            </Button>
                          ))}
                        </Space>
                      </div>

                      {/* 新闻舆情优化 */}
                      <div>
                        <Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>新闻舆情：</Text>
                        <Space wrap size="small">
                          {quickRefineOptions.newsOpinion.map(option => (
                            <Button
                              key={option.key}
                              size="small"
                              onClick={() => handleQuickRefine(option)}
                              loading={isRefining}
                              disabled={isRefining}
                            >
                              <span>{option.icon} {option.label}</span>
                            </Button>
                          ))}
                        </Space>
                      </div>

                      {/* 格式调整 */}
                      <div>
                        <Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>格式调整：</Text>
                        <Space wrap size="small">
                          {quickRefineOptions.format.map(option => (
                            <Button
                              key={option.key}
                              size="small"
                              onClick={() => {
                                if (option.isCustom) {
                                  handleCustomFormat();
                                } else {
                                  handleQuickRefine(option);
                                }
                              }}
                              loading={isRefining}
                              disabled={isRefining}
                            >
                              <span>{option.icon} {option.label}</span>
                            </Button>
                          ))}
                        </Space>
                      </div>

                      {/* 自定义输入 */}
                      <Divider style={{ margin: '8px 0', fontSize: 12 }}>或输入自定义要求</Divider>
                      <Space.Compact style={{ width: '100%' }}>
                        <Input
                          placeholder="例如：把第二段改得更简洁，增加具体案例..."
                          value={refineInput}
                          onChange={(e) => setRefineInput(e.target.value)}
                          onPressEnter={handleCustomRefine}
                          disabled={isRefining}
                        />
                        <Button
                          type="primary"
                          onClick={handleCustomRefine}
                          loading={isRefining}
                          disabled={isRefining}
                        >
                          应用微调
                        </Button>
                      </Space.Compact>

                      {/* 微调历史 */}
                      {refineHistory.length > 0 && (
                        <>
                          <Divider style={{ margin: '12px 0' }}>微调历史</Divider>
                          <div style={{ maxHeight: 150, overflowY: 'auto' }}>
                            {refineHistory.map((item, index) => (
                              <Alert
                                key={index}
                                message={
                                  <Space>
                                    <Text strong style={{ fontSize: 12 }}>{item.timestamp}</Text>
                                    <Text type="secondary" style={{ fontSize: 12 }}>-</Text>
                                    <Text style={{ fontSize: 12 }}>{item.requirement}</Text>
                                  </Space>
                                }
                                type="success"
                                icon={<CheckCircleOutlined />}
                                style={{ marginBottom: 8, fontSize: 12 }}
                                closable
                                onClose={() => {
                                  setRefineHistory(prev => prev.filter((_, i) => i !== index));
                                }}
                              />
                            ))}
                          </div>
                        </>
                      )}

                      {/* 版本管理 */}
                      {contentVersions.length > 0 && (
                        <>
                          <Divider style={{ margin: '12px 0' }}>版本历史</Divider>
                          <Space wrap>
                            {contentVersions.map((v) => (
                              <Button
                                key={v.version}
                                size="small"
                                type={v.version === currentVersion ? 'primary' : 'default'}
                                onClick={() => handleVersionRollback(v.version)}
                                disabled={v.version === currentVersion}
                              >
                                版本 {v.version}
                                {v.version === currentVersion && ' (当前)'}
                              </Button>
                            ))}
                          </Space>
                        </>
                      )}
                    </Space>
                  </Card>
                )}

                {/* 操作按钮 - 移到Card的extra中，不占用主体空间 */}
                {false && (
                  <div style={{ marginTop: 12 }}>
                    <Space size="small">
                      <Button
                        icon={<SwapOutlined />}
                        onClick={handleModelComparison}
                        disabled={!content.trim()}
                      >
                        多模型对比
                      </Button>
                      <Button
                        icon={<BugOutlined />}
                        onClick={handleDebugPanel}
                      >
                        调试面板
                      </Button>
                      <Button
                        icon={<SafetyCertificateOutlined />}
                        onClick={() => checkContentQuality(generatedContent)}
                        disabled={!generatedContent}
                      >
                        质量检测
                      </Button>
                    </Space>
                  </div>
                )}
              </div>
            </TabPane>
            
            {/* 话题详情标签页 */}
            <TabPane 
              tab={
                <Space>
                  <FileTextOutlined />
                  话题详情
                </Space>
              } 
              key="detail"
            >
              <div style={{ padding: '16px' }}>
                <Title level={4}>{item.title}</Title>
                
                {detailData && (
                  <div className="detail-stats">
                    <Space size="large">
                      {detailData.view_count !== undefined && (
                        <span><EyeOutlined /> {detailData.view_count}</span>
                      )}
                      {detailData.like_count !== undefined && (
                        <span><LikeOutlined /> {detailData.like_count}</span>
                      )}
                      {detailData.comment_count !== undefined && (
                        <span><CommentOutlined /> {detailData.comment_count}</span>
                      )}
                      {detailData.share_count !== undefined && (
                        <span><ShareAltOutlined /> {detailData.share_count}</span>
                      )}
                    </Space>
                  </div>
                )}
                
                {item.excerpt && (
                  <Paragraph>{item.excerpt}</Paragraph>
                )}
                
                {detailData?.content && (
                  <>
                    <Divider />
                    <Paragraph>{detailData.content}</Paragraph>
                  </>
                )}
                
                {detailData?.tags && detailData.tags.length > 0 && (
                  <>
                    <Divider />
                    <Space wrap>
                      {detailData.tags.map((tag) => (
                        <Tag key={tag}>{tag}</Tag>
                      ))}
                    </Space>
                  </>
                )}
              </div>
            </TabPane>
            
            {/* 评论参考标签页 */}
            <TabPane 
              tab={
                <Space>
                  <CommentOutlined />
                  评论参考
                  {detailData?.comments && (
                    <Badge count={detailData.comments.length} />
                  )}
                </Space>
              } 
              key="comments"
            >
              <div style={{ padding: '16px' }}>
                {detailData?.comments && detailData.comments.length > 0 ? (
                  <>
                    <Alert
                      message="提示"
                      description='点击评论右侧的"引用"按钮，可将评论内容添加到创作参考中'
                      type="info"
                      showIcon
                      style={{ marginBottom: 16 }}
                    />
                    {renderComments(detailData.comments)}
                  </>
                ) : (
                  <div style={{ textAlign: 'center', padding: '20px' }}>
                    <Text type="secondary">暂无评论数据</Text>
                  </div>
                )}
              </div>
            </TabPane>
            
            {/* 热度趋势标签页 */}
            <TabPane 
              tab={
                <Space>
                  <FireOutlined />
                  热度趋势
                </Space>
              } 
              key="trend"
            >
              <div style={{ padding: '16px' }}>
                <HeatTrendChart itemId={item.item_id} />
              </div>
            </TabPane>
          </Tabs>
        </div>
      </Spin>
      
      {/* ========== 弹窗组件 ========== */}
      
      {/* 提示词库 */}
      <Modal
        title="选择提示词模板"
        open={promptLibraryVisible}
        onCancel={() => setPromptLibraryVisible(false)}
        width={900}
        footer={null}
      >
        <PromptLibrary 
          onSelect={handlePromptSelect}
          onPreview={(template) => {
            selectPrompt(template.id);
            setPromptEditorVisible(true);
          }}
        />
      </Modal>
      
      {/* 提示词编辑器 */}
      <Drawer
        title="编辑提示词"
        placement="right"
        open={promptEditorVisible}
        onClose={() => setPromptEditorVisible(false)}
        width={600}
      >
        {currentPrompt && (
          <PromptEditor
            value={currentPrompt.systemPrompt}
            template={currentPrompt}
            onChange={(value) => console.log('Changed:', value)}
            onSave={(value) => {
              updatePrompt(currentPrompt.id, { systemPrompt: value });
              message.success('提示词已保存');
              setPromptEditorVisible(false);
            }}
          />
        )}
      </Drawer>
      
      {/* 多模型对比 */}
      <Modal
        title="多模型对比生成"
        open={modelComparisonVisible}
        onCancel={() => setModelComparisonVisible(false)}
        width={1200}
        footer={null}
        bodyStyle={{ height: '60vh', overflow: 'auto' }}
      >
        <ModelComparison 
          hotItemId={item?.item_id}
          platform={item?.platform}
          onCompare={(results) => {
            console.log('多模型对比完成:', results);
            // 可以在这里处理对比结果
          }}
        />
      </Modal>

      {/* 调试面板 */}
      <Modal
        title="多模型调试面板"
        open={debugPanelVisible}
        onCancel={() => setDebugPanelVisible(false)}
        width={1400}
        footer={null}
        bodyStyle={{ height: '70vh', overflow: 'auto' }}
      >
        <MultiModelDebugPanel />
      </Modal>
      
      {/* 优化建议 */}
      <Drawer
        title="智能优化建议"
        placement="right"
        open={optimizationVisible}
        onClose={() => setOptimizationVisible(false)}
        width={500}
      >
        <OptimizationPanel 
          content={generatedContent}
          onApply={handleApplyOptimization}
        />
      </Drawer>
      
      {/* 参数设置 */}
      <Drawer
        title="生成参数设置"
        placement="right"
        open={parameterVisible}
        onClose={() => setParameterVisible(false)}
        width={400}
      >
        <ParameterPanel
          parameters={parameters}
          onChange={setParameters}
        />
      </Drawer>

      {/* 自定义格式设置 */}
      <Modal
        title="自定义格式要求"
        open={customFormatVisible}
        onCancel={() => setCustomFormatVisible(false)}
        onOk={handleApplyCustomFormat}
        width={600}
        okText="应用格式"
        cancelText="取消"
        confirmLoading={isRefining}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Alert
            message="格式说明"
            description="请输入格式要求，AI将按照您的要求重新组织内容格式。输出格式将保持Word文档兼容性。"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <TextArea
            value={customFormatInput}
            onChange={(e) => setCustomFormatInput(e.target.value)}
            placeholder="例如：一级标题黑体三号，正文仿宋小四号等"
            rows={8}
            style={{ fontFamily: 'monospace' }}
          />
          <Text type="secondary" style={{ fontSize: 12 }}>
            提示：可以指定标题层级、字体、字号、对齐方式、缩进等格式要求
          </Text>
        </Space>
      </Modal>

      {/* 内容微调抽屉 */}
      <Drawer
        title="内容微调"
        placement="right"
        open={refineDrawerVisible}
        onClose={() => setRefineDrawerVisible(false)}
        width={isMobile ? '90%' : 600}
      >
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {/* 快速优化按钮 */}
          <div>
            <Text type="secondary" style={{ marginBottom: 8, display: 'block' }}>基础优化：</Text>
            <Space wrap size="small">
              {quickRefineOptions.basic.map(option => (
                <Button
                  key={option.key}
                  size="small"
                  onClick={() => handleQuickRefine(option)}
                  loading={isRefining}
                  disabled={isRefining}
                >
                  <span>{option.icon} {option.label}</span>
                </Button>
              ))}
            </Space>
          </div>

          {/* 新闻舆情优化 */}
          <div>
            <Text type="secondary" style={{ marginBottom: 8, display: 'block' }}>新闻舆情：</Text>
            <Space wrap size="small">
              {quickRefineOptions.newsOpinion.map(option => (
                <Button
                  key={option.key}
                  size="small"
                  onClick={() => handleQuickRefine(option)}
                  loading={isRefining}
                  disabled={isRefining}
                >
                  <span>{option.icon} {option.label}</span>
                </Button>
              ))}
            </Space>
          </div>

          {/* 格式调整 */}
          <div>
            <Text type="secondary" style={{ marginBottom: 8, display: 'block' }}>格式调整：</Text>
            <Space wrap size="small">
              {quickRefineOptions.format.map(option => (
                <Button
                  key={option.key}
                  size="small"
                  onClick={() => {
                    if (option.isCustom) {
                      handleCustomFormat();
                    } else {
                      handleQuickRefine(option);
                    }
                  }}
                  loading={isRefining}
                  disabled={isRefining}
                >
                  <span>{option.icon} {option.label}</span>
                </Button>
              ))}
            </Space>
          </div>

          {/* 自定义输入 */}
          <Divider style={{ margin: '16px 0' }}>或输入自定义要求</Divider>
          <Space.Compact style={{ width: '100%' }}>
            <Input
              placeholder="例如：把第二段改得更简洁，增加具体案例..."
              value={refineInput}
              onChange={(e) => setRefineInput(e.target.value)}
              onPressEnter={handleCustomRefine}
              disabled={isRefining}
            />
            <Button
              type="primary"
              onClick={handleCustomRefine}
              loading={isRefining}
              disabled={isRefining}
            >
              应用微调
            </Button>
          </Space.Compact>

          {/* 微调历史 */}
          {refineHistory.length > 0 && (
            <>
              <Divider style={{ margin: '16px 0' }}>微调历史</Divider>
              <div style={{ maxHeight: 300, overflowY: 'auto' }}>
                {refineHistory.map((item, index) => (
                  <Alert
                    key={index}
                    message={
                      <Space>
                        <Text strong style={{ fontSize: 12 }}>{item.timestamp}</Text>
                        <Text type="secondary" style={{ fontSize: 12 }}>-</Text>
                        <Text style={{ fontSize: 12 }}>{item.requirement}</Text>
                      </Space>
                    }
                    type="success"
                    icon={<CheckCircleOutlined />}
                    style={{ marginBottom: 8 }}
                    closable
                    onClose={() => {
                      setRefineHistory(prev => prev.filter((_, i) => i !== index));
                    }}
                  />
                ))}
              </div>
            </>
          )}

          {/* 版本管理 */}
          {contentVersions.length > 0 && (
            <>
              <Divider style={{ margin: '16px 0' }}>版本历史</Divider>
              <Space wrap>
                {contentVersions.map((v) => (
                  <Button
                    key={v.version}
                    size="small"
                    type={v.version === currentVersion ? 'primary' : 'default'}
                    onClick={() => handleVersionRollback(v.version)}
                    disabled={v.version === currentVersion}
                  >
                    版本 {v.version}
                    {v.version === currentVersion && ' (当前)'}
                  </Button>
                ))}
              </Space>
            </>
          )}

          {/* 高级操作 */}
          <Divider style={{ margin: '16px 0' }}>高级操作</Divider>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Button
              block
              icon={<SwapOutlined />}
              onClick={() => {
                setRefineDrawerVisible(false);
                handleModelComparison();
              }}
              disabled={!content.trim()}
            >
              多模型对比
            </Button>
            <Button
              block
              icon={<SafetyCertificateOutlined />}
              onClick={() => checkContentQuality(generatedContent)}
              disabled={!generatedContent}
            >
              质量检测
            </Button>
            <Button
              block
              icon={<BugOutlined />}
              onClick={() => {
                setRefineDrawerVisible(false);
                handleDebugPanel();
              }}
            >
              调试面板
            </Button>
          </Space>
        </Space>
      </Drawer>

      {/* 段落选择器抽屉 */}
      <Drawer
        title="选择段落组合文章"
        placement="right"
        open={showParagraphSelector}
        onClose={() => setShowParagraphSelector(false)}
        width={isMobile ? '90%' : 700}
        footer={
          <Space style={{ float: 'right' }}>
            <Button onClick={() => toggleAllParagraphs(false)}>取消全选</Button>
            <Button onClick={() => toggleAllParagraphs(true)}>全选</Button>
            <Button type="primary" onClick={composeArticle} icon={<FileTextOutlined />}>
              组合文章 ({contentParagraphs.filter(p => p.selected).length} 个段落)
            </Button>
          </Space>
        }
      >
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <Alert
            message="段落选择"
            description={`选择您想要保留的段落，然后点击"组合文章"按钮生成最终文章。共检测到 ${contentParagraphs.length} 个段落。`}
            type="info"
            showIcon
          />
          {contentParagraphs.map((para, index) => (
            <Card
              key={para.id}
              size="small"
              style={{
                border: para.selected ? '2px solid #1890ff' : '1px solid #d9d9d9',
                cursor: 'pointer',
                transition: 'all 0.3s'
              }}
              onClick={() => toggleParagraphSelection(para.id)}
              hoverable
            >
              <Space style={{ width: '100%', alignItems: 'flex-start' }}>
                <input
                  type="checkbox"
                  checked={para.selected}
                  onChange={(e) => {
                    e.stopPropagation();
                    toggleParagraphSelection(para.id);
                  }}
                  style={{ marginTop: '4px' }}
                />
                <div style={{ flex: 1 }}>
                  <Text strong style={{ display: 'block', marginBottom: 8 }}>
                    段落 {index + 1}
                    {para.selected && (
                      <Tag color="blue" style={{ marginLeft: 8 }}>已选中</Tag>
                    )}
                  </Text>
                  <Paragraph
                    style={{ marginBottom: 0 }}
                    ellipsis={{ rows: 3, expandable: true, symbol: '展开' }}
                  >
                    {para.content}
                  </Paragraph>
                </div>
              </Space>
            </Card>
          ))}

          {contentParagraphs.length === 0 && (
            <Empty
              description="暂无段落数据"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Space>
      </Drawer>
    </Modal>
  );
};

export default HotCreatorModal;